const app = getApp()

const getparamHandle = (data = {}) => {
  let paramsStr = "?";
  for (var key in data) {
    if (data[key] == null || data[key] == 'null') {
      continue;
    }
    paramsStr += key + "=" + data[key] + '&';
  }
  return paramsStr;
}

const request = (url, options) => {
  return new Promise((resolve, reject) => {
    let header = {
      'Content-Type': options.ContentType,
      'x-access-token': app.globalData.userToken,
      'x-access-employeeid': app.globalData.userEmployeeId,
      'x-access-companyid': app.globalData.userCompanyId
    }
    if (options.method === 'get') {
      header = {
        'x-access-token': app.globalData.userToken,
        'x-access-employeeid': app.globalData.userEmployeeId,
        'x-access-companyid': app.globalData.userCompanyId
      }
    }
    wx.request({
      url: `${app.globalData.baseURL}${url}`,
      method: options.method,
      data: options.data,
      header: header,
      success(res) {
        if (app.globalData.pringLog) {
          console.log('')
          console.log('%c请求地址：' + url, 'color: yellow;');
          console.log('%c请求方式：' + options.method, 'color:green');
          if (options.data != undefined && options.data != null) {
            console.log('%c请求参数：' + JSON.stringify(options.data), 'color:#ec7259');
          }
          console.log('响应结果:', res.data)
        }
        if(res.statusCode===401){
            wx.navigateTo({
              url: '/pages/login/login-index/login-index',
            })
            return;
        }
        if (res.data.code===200) {
          resolve(res.data)
        } else {
            wx.showToast({
              icon: 'none',
              title: res.data.msg
            })
            reject(res)
        }
      },
      fail(error) {
        if (app.globalData.pringLog) {
          console.log('')
          console.log('%c请求地址：' + url, 'color: yellow;');
          console.log('%c请求方式：' + options.method);
          console.log('%c请求参数：' + options.data, 'color:#ec7259');
          console.log('错误结果:', error)
        }
        reject(error.data)
      }
    })
  })
}

const get = (url, data = null) => {
  if (data !== null && data !== undefined) {
    url += getparamHandle(data);
  }
  return request(url, {
    method: 'get'
  })
}

const post = (url, data, isForm = false) => {
  if (isForm) {
    return request(url, {
      method: 'POST',
      data: data,
      ContentType: 'application/x-www-form-urlencoded'
    })
  } else {
    return request(url, {
      method: 'POST',
      data: JSON.stringify(data),
      ContentType: 'application/json; charset=UTF-8'
    })
  }
}

const put = (url, data) => {
  return request(url, {
    method: 'PUT',
    data: JSON.stringify(data),
    ContentType: 'application/json; charset=UTF-8'
  })
}

const remove = (url, data) => {
  return request(url, {
    method: 'DELETE',
    data: JSON.stringify(data)
  })
}

module.exports = {
  get,
  post,
  put,
  remove
}